package com.xt.base.acegi;

/**
 *  <br>
 * <br>
 * 
 * <p>
 * <a href="ValidationCodeFilter.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @create-date:2010-7-21
 */
import javax.servlet.http.HttpServletRequest;

import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;

public class ValidationCodeFilter extends AuthenticationProcessingFilter {
	public Authentication attemptAuthentication(HttpServletRequest request)
			throws AuthenticationException {
		String inputValidationCode = request.getParameter("chknumber");
		// 从Session中取出验证码
		String ssnValidationCode = (String) request.getSession().getAttribute(
				"VALIDATION_CODE");
		if(ssnValidationCode==null) ssnValidationCode="";
		if(inputValidationCode==null) inputValidationCode="";
		// 取出后就失效，
		request.getSession().setAttribute("VALIDATION_CODE", "Game Over");
		ssnValidationCode = ssnValidationCode.toLowerCase();
		inputValidationCode = inputValidationCode.toLowerCase();
		
		String username = obtainUsername(request);
        String password = obtainPassword(request);
		 // Place the last username attempted into HttpSession for views
        request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, username);
		
		if (ssnValidationCode == null
				|| ssnValidationCode.equalsIgnoreCase("Game Over")
				|| !ssnValidationCode.equals(inputValidationCode)) {
			// 用户输入的值与看到的不一致,抛出异常

			throw new ValidationCodeException("验证码输入错误!");
		}
		
        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
	}
}
